//
//  WFHomeTVC.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/9.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit

import SVProgressHUD
//  重用标记
private let WFHomeTVCellIdentifier = "WFHomeTVCellIdentifier"
class WFHomeTVC: WFVisitorTVC {
    // MARK:  - 懒加载控件
    //  微博数据列表
  private lazy var statusListViewModel:WFStatusListViewModel = WFStatusListViewModel()
    
    //tiplabel
    private lazy var tipLabel:UILabel = {
        let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 12)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = .Center
        label.hidden = true
        return label
        
    }()
    
    //上拉加载更多控件
    private lazy var pullUpView:UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.darkGrayColor()
        return indicator
    }()
    
    //下拉刷新控件(系统的)
//    private lazy var pullDownView:UIRefreshControl = {
//        let ctr = UIRefreshControl()
//        
//        //添加下拉刷新(系统的)
//        ctr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
//        return ctr
//    }()
    
    //自定义的下拉刷新!
    private lazy var pullDownView:WFRefreshControl = {
        let ctr = WFRefreshControl()
        
        //添加下拉刷新(系统的)
        ctr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        return ctr
    }()
    
    //定义下拉刷新的方法
    @objc private func pullDownRefresh(){
        loadStatus()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if isLogin{
            setUpUI()
            setUpTableview()
            loadStatus()
        }else{
            visitorView?.loadVisitorinfo(nil, imgName: nil)
        }
    }
    private func setUpUI(){
        guard let nav = self.navigationController else {
            return
        }
        
        nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        tipLabel.frame = CGRectMake(0, 64-30,nav.navigationBar.width, 30)
     }
    
    // MARK:  - 开启tip的动画
    private func startAnimation(message:String){
        if tipLabel.hidden == false {
            return
        }
        
        tipLabel.hidden = false
        tipLabel.text = message
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        }
    }
    
    // MARK:  - 设置tableView的相关属性
    func setUpTableview(){
        tableView.registerClass(WFStatusTableViewCell.self, forCellReuseIdentifier: WFHomeTVCellIdentifier)
        tableView.separatorStyle = .None
       // MARK:  -  先暂时写一个高度吧
        tableView.rowHeight = UITableViewAutomaticDimension
        // 预估行高
        tableView.estimatedRowHeight = 200
        
        //添加footview来承载上拉加载更多
        tableView.tableFooterView = pullUpView
        //指定大小
        pullUpView.sizeToFit()
        
        //集成系统的下拉刷新
        //第一种方式,必须在tableViewController里
//        self.refreshControl = pullDownView
        
        //第二种方式,需要在tableView里
        tableView.addSubview(pullDownView)
    }
    
    // MARK:  - 终止刷新
    private func endRefresh(){
        pullUpView.stopAnimating()
        pullDownView.endRefreshing()
    }
    // MARK:  - 联网请求数据
    func loadStatus(){
//         SVProgressHUD.show()

        self.statusListViewModel.loadStatus(pullUpView.isAnimating()) { (isSuccess, pullRefreshInfoMessage) -> () in
            if !self.pullUpView.isAnimating(){
                //开启tip动画
                self.startAnimation(pullRefreshInfoMessage)
                print("开启动画")
            }
            self.endRefresh()
            if isSuccess {
                
                //请求数据成功了,我就刷新数据
                self.tableView.reloadData()
                
            }
        }
    }
    


}

extension WFHomeTVC {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(WFHomeTVCellIdentifier, forIndexPath: indexPath) as! WFStatusTableViewCell
        
        cell.statusViewModel = statusListViewModel.statusList[indexPath.row]
        cell.selectionStyle = .None
        return cell
        
        
        
    }
    
    //将要显示的那个cell
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullUpView.isAnimating() {
            //开启菊花转!
            pullUpView.startAnimating()
            
            //人为延迟两秒
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
                Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                    
                    print("疯狂菊花转!")
                    //联网请求数据
                    self.loadStatus()
            })
            
         
        }
    }
}
